//index.js
var app = getApp();
var that;
var chatListData = [];
Page({
  data: {
    askWord: '',
    userInfo: {},
    chatList: [],
    scrolltop:'',
    userLogoUrl:'/res/image/me.jpg',
    aiAnswer: '',
    agentList: [],
    nowAgent: {},
    timeSlotId: '',
  },
  onLoad: function () {
    const self = this;
    var info = wx.getStorageSync("userinfo");
    //当本地缓存的用户名称不为""或者null时，设置userinfo信息
    if(info.nickName != '' && info.nickName != null){
      this.setData({
          userInfo: info,
      })
    }

    wx.request({
      url: 'http://47.120.31.85:8080/word/getAllAgent',
      method: 'GET',
      success: function(res) {
        console.log(res)
        self.setData({
          agentList: res.data.data,
          nowAgent: res.data.data[0]
        })
      }
    })
  },
  onReady: function () {
    const self = this;
    setTimeout(function () {
      self.addChat('欢迎来到中国智汇学习平台,一起探索中华文化和动人故事吧!', 'l');
    }, 1000);
  },
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&  this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2     //这里的数字设置当前页面在tabbar里对应的序列，从0开始
      })
    }
  },
  Typing:function(e){
    const self = this;
    self.setData({
      askWord: e.detail.value,
    })
  },

  sendChat: function (e) {
    const self = this;
    clearInterval(self.data.timeSlotId)
    let answer = '';
    let str = '';
    self.addChat(this.data.askWord, 'r');
    self.addChat('', 'l');
    const id = setInterval(() => {
      var charlenght = chatListData.length;
      let copyChatList = self.data.chatList;
      if ( copyChatList[charlenght - 1].text.length < answer.length ) {
        let nowLen = copyChatList[charlenght - 1].text.length;
        copyChatList[charlenght - 1].text = answer.slice(0,nowLen+1)
        self.setData({
          chatList: copyChatList,
          scrolltop: "roll" + charlenght,
        });
      }
    },70);
    self.setData({
      timeSlotId: id
    })
    const requestTask = wx.request({
      url: "http://localhost:8080/word/characterSimulationChat?question=" + self.data.askWord + "&agentId=" + self.data.nowAgent.agentId + "&username=" + self.data.userInfo.nickName, // 需要请求的接口地址
      enableChunked: true, // enableChunked必须为true
      method: "GET",
      timeout: '120000',
      success(res) {
        console.log(res.data)
      },
      fail: function (error) {
        // 请求失败的操作
        console.error(error);
      },
      complete: function () {
        // 请求完成的操作，无论成功或失败都会执行
        console.log('请求完成', str);
      }
    })
    // 监听服务端返回的数据
    requestTask.onChunkReceived(res => {
      // Uint8Array转为text格式
      let arrayBuffer = res.data;
      let decoder = new TextDecoder('utf-8');
      let text = decoder.decode(arrayBuffer);
      //let text = that.arrayBufferToString(arrayBuffer)//真机使用
      //正则匹配上所有event:data后面的文字
      const eventRegex = /event:data\ndata:"data:(.*?)"/g;
      const eventRegexErr = /event:600\ndata:"(.*?)"/g;
      let matches = [];
      let match;
      if (text.indexOf('600') != -1) {//如果获取响应失败
        while ((match = eventRegexErr.exec(text)) !== null) {
          wx.showToast({
            title: match[1],
          })
          matches.push(match[1]);
        }
        str = str + matches.join('')
      } else {//如果获取响应成功
        while ((match = eventRegex.exec(text)) !== null) {
          matches.push(match[1]);
        }
        //处理成字符串
        str = str + matches.join('')
        if (text.substr(0,5) == 'data:') {
          text = text.substr(5)
        }
        answer = this.dealAnswer(text,answer);
      }
    })


    self.setData({
      askWord: '',
      aiAnswer: '',
    });
  },
  dealAnswer(data,answer) {
    let sseData = '';
    for ( let i = 0 ; i < data.length ; i ++ ) {
      if (data[i] != '\n') {
        sseData += data[i];
      }
    }
    sseData = sseData.replaceAll("&#32;", " ").replaceAll("&#92n", "")
    answer += sseData;
    return answer;
  },
  addChat: function (word, orientation) {
    const self = this;
    let ch = { 'text': word, 'time': new Date().getTime(), 'orientation': orientation };
    chatListData.push(ch);
    var charlenght = chatListData.length;
    self.setData({
      chatList: chatListData,
      scrolltop: "roll" + charlenght,
    });
  }
})